'use strict';

const MongoClient = require('mongodb').MongoClient;
const logger = require('./cli-log');

class Mongo {
  constructor(url, dbName) {
    this.url = url;
    this.dbName = dbName;
  }

  connect() {
    console.log(this.url);
    return new Promise(async (resolve, reject) => {
      const client = new MongoClient(this.url);
      client.connect().then(() => {
        const db = client.db(this.dbName);
        resolve({ db, client });
      }).catch(err => {
        reject(err);
      });
      // MongoClient.connect(
      //   this.url,
      //   (err, client) => {
      //     console.log('链接成功');
      //     if (err) {
      //       reject(err);
      //     } else {
      //       const db = client.db(this.dbName);
      //       console.log(db, 'jjjj');
      //       ;
      //     }
      //   });
    });
  }

  connectAction(docName, action) {
    return new Promise(async (resolve, reject) => {
      const { db, client } = await this.connect();
      try {
        const collection = db.collection(docName);
        action(collection, result => {
          console.log(result, 'result');
          this.close(client);
          logger.verbose('result', result);
          resolve(result);
        }, err => {
          this.close(client);
          logger.error(err.toString());
          reject(err);
        });
      } catch (err) {
        this.close(client);
        logger.error(err.toString());
        reject(err);
      }
    });
  }

  query(docName) {
    return this.connectAction(docName, async (collection, onSuccess, onError) => {
      const res = await collection.find({}, { projection: { _id: 0 } }).toArray();
      onSuccess(res);
    });
  }

  insert(docName, data) {
    return this.connectAction(docName, (collection, onSuccess, onError) => {
      collection.insertMany(data, (err, result) => {
        if (err) {
          onError(err);
        } else {
          onSuccess(result);
        }
      });
    });
  }

  remove(docName, data) {
    return this.connectAction(docName, (collection, onSuccess, onError) => {
      collection.deleteOne(data, (err, result) => {
        if (err) {
          onError(err);
        } else {
          onSuccess(result);
        }
      });
    });
  }

  update(collection, data) {
  }

  close(client) {
    client && client.close();
  }
}

module.exports = Mongo;
